﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace CSF.Utility.Mvc
{
    public static class UrlUtility
    {
        /// <summary>
        /// 在Url后面追加参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramName"></param>
        /// <param name="paramValue"></param>
        /// <param name="noreplace">不替换已有的参数，默认为false</param>
        /// <returns></returns>
        public static string AppendParameter(string url, string paramName, string paramValue, bool noreplace= false)
        {
            if (!noreplace)
            {
                string pattern = "(?<=[?&])" + paramName + "=[^&]*";
                url = Regex.Replace(url, pattern, "");
            }
            if (url.Contains('?'))
            {
                url += "&";
            }
            else
            {
                url += "?";
            }
            url += paramName + "=" + Uri.EscapeDataString(paramValue);
            return url;
        }

        /// <summary>
        /// 判断url是否以startpath开头，假设url和startpath都是以"/"开头
        /// </summary>
        /// <param name="url"></param>
        /// <param name="startpath"></param>
        /// <returns></returns>
        public static bool IsStartWithPath(string url, string startpath)
        {
            string pattern = "^" + startpath + "(?![^?/])";
            return Regex.IsMatch(url, pattern);
        }
    }
}
